const app =getApp({})
// 定义全局 requestTask
let requestTask = null;
Page({
    data: {
      isDarkMode: false,
      inputText: '',
      selectedTemplates: [],
      aiAvatar: 'https://android-artworks.25pp.com/fs08/2024/08/15/6/110_dd6afbec6367e0e26766f6f74149b879_con.png',
      userAvatar: 'https://img0.baidu.com/it/u=1735983494,3068353037&fm=253&fmt=auto&app=138&f=JPEG?w=800&h=800',
      chatHistory: [
        
      ],
      quickTemplates: ['如何解这道题？', '能详细解释一下吗？', '我还是不太明白', '谢谢你的解答'],
      userQueation:'',
      examPleSentence:[
          '介绍一下如何提高英语阅读能力',
          '帮我用Java写一个水仙花数的代码'
      ],
      messages: [{ content: '' }], // 初始化为一个包含一个空对象的数组
      toToxmlFlag :false,
      categories: [],
      selecteDbId:"",
      startFlag:0

    },
    onLoad(){
        if(wx.getStorageSync('userInfo')){
            this.setData({
                userInfo:wx.getStorageSync('userInfo')
            })
        }
        this.setData({
            startFlag:app.globalData.startFlag
        })
    },
    /* 点击一个案例询问 */
    clickQuestionExample(e){
        var questionTemp = e.currentTarget.dataset.question
        this.setData({
            userQueation:questionTemp
        })
    },
    toggleDarkMode() {
      this.setData({
        isDarkMode: !this.data.isDarkMode
      });
    },
  
    handleScroll(e) {
      this.setData({
        scrollTop: e.detail.scrollTop
      });
    },
  
    handleInput(e) {
      this.setData({
        userQueation: e.detail.value
      });
    },
  
   

    handleSend() {
        if (!this.data.userQueation.trim()) {
            wx.showToast({
                title: '请输入问题',
                icon: 'none'
            });
            return;
        }
    
        // ✅ 终止上一次的请求，防止冲突
        if (this.requestTask) {
            console.log('终止上一次的请求');
            this.requestTask.abort(); // 主动终止未完成的请求
            this.requestTask = null; // ✅ 关键：重置，避免影响后续请求
        }
    
        // ✅ 生成 request_id 防止错乱
        const requestId = Date.now().toString();
    
        const newMessage = {
            role: 'user',
            content: this.data.userQueation,
            time: new Date().toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
        };
        // ✅ 修复 chatHistory 结构，防止数据被错误覆盖
        let updatedChatHistory = [...this.data.chatHistory, newMessage];
        this.setData({
            chatHistory: [...this.data.chatHistory, newMessage],
            userQueation: '',
            toToxmlFlag: false
        });
    
        console.log("发送的 chatHistory: ", updatedChatHistory);
    
        // 添加助手消息对象
        const assistantObj = {
            role: "assistant",
            content: "",
            time: new Date().toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' }),
            markdowmFlag: false
        };
    
        this.setData({
            chatHistory: [...this.data.chatHistory, assistantObj],
        });
    
        const that = this;
        let buffer = '';  // ✅ 清空 buffer，防止旧数据污染
        
        // ✅ 发送请求
        this.requestTask = wx.request({
            url: app.globalData.baseUrl + '/admin/chatstream',
            method: 'POST',
            header: {
                'Content-Type': 'application/json',
            },
            data: {
                user_name: wx.getStorageSync('userInfo').name, // 假设用户ID存储在本地
                user_major:wx.getStorageSync('UserInfo').college,
                message: this.data.chatHistory,
                stream: true, // 流式请求
                request_id: requestId // ✅ 传递 request_id
            },
            enableChunked: true,
            success: (res) => {
                console.log("请求成功", res);
            },
            fail: (err) => {
                console.error("请求失败", err);
                wx.showToast({
                    title: '网络异常，请稍后重试',
                    icon: 'none'
                });
            },
            complete: () => {
                console.log('请求完成（完成回调）');
                if (typeof that.towxmlTranform === 'function') {
                    that.towxmlTranform();
                }
            }
        });
        function base64Decode(input) {
            const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
            let str = '';
            let bytes = [];
            let enc1, enc2, enc3, enc4;
            let i = 0;
        
            input = input.replace(/[^A-Za-z0-9\+\/\=]/g, '');
        
            while (i < input.length) {
                enc1 = chars.indexOf(input.charAt(i++));
                enc2 = chars.indexOf(input.charAt(i++));
                enc3 = chars.indexOf(input.charAt(i++));
                enc4 = chars.indexOf(input.charAt(i++));
        
                bytes.push((enc1 << 2) | (enc2 >> 4));
                if (enc3 !== 64) {
                    bytes.push(((enc2 & 15) << 4) | (enc3 >> 2));
                }
                if (enc4 !== 64) {
                    bytes.push(((enc3 & 3) << 6) | enc4);
                }
            }
        
            bytes.forEach(byte => {
                str += String.fromCharCode(byte);
            });
        
            return str;
        }
        this.requestTask.onChunkReceived((chunk) => {
            if (chunk.data instanceof ArrayBuffer) {
                try {
                    const base64Data = wx.arrayBufferToBase64(chunk.data);
                    const decodedData = base64Decode(base64Data);
                    buffer += decodedData;
                    const messagesTemp = buffer.split('\n');
                    buffer = messagesTemp.pop();
            
                    messagesTemp.forEach(message => {
                        if (message.startsWith('data:')) {
                            const jsonMessage = message.substring(5).trim();
                            if (jsonMessage) {
                                try {
                                    const parsedMessage = JSON.parse(jsonMessage);
                                    if (parsedMessage.content) {
                                        const updatedMessages = that.data.chatHistory;
                                        const lastMessageIndex = updatedMessages.length - 1;
                                        updatedMessages[lastMessageIndex].content += parsedMessage.content;
                                        that.setData({ chatHistory: updatedMessages });
                                    }
            
                                    if (parsedMessage.hasOwnProperty('done') && parsedMessage.done) {
                                        if (typeof that.towxmlTranform === 'function') {
                                            that.towxmlTranform();
                                        }
                                    }
                                } catch (e) {
                                    console.error('JSON 解析失败:', e);
                                }
                            }
                        }
                    });
                } catch (e) {
                    console.error('分块处理出错:', e);
                }
            }
            
        });
    },
    

/* ✅ 将内容转换为富文本 */
    towxmlTranform() {
        console.log('触发转换');

        if (!app.towxml) {
            console.error('towxml 未初始化');
            return;
        }

        let temp = this.data.chatHistory;
        let lastIndex = temp.length - 1;
        let tempContent = temp[lastIndex].content;

        if (!tempContent) {
            console.warn('没有可转换的内容');
            return;
        }

        try {
            // ✅ 调用 towxml 解析 Markdown
            const result = app.towxml(tempContent, 'markdown');
            if (result) {
                temp[lastIndex].contentMarkdowm = result;
                temp[lastIndex].markdowmFlag = true;
                temp[lastIndex].content = tempContent;
                // ✅ 防止被重置，增加状态锁
                this.setData({
                    toToxmlFlag: true,
                    chatHistory: temp
                });

                console.log('转换结果:', this.data.chatHistory);
            } else {
                console.warn('Markdown 解析返回空');
            }
        } catch (e) {
            console.error('towxml 转换失败:', e);
        }
    },

  
    toggleTemplate(e) {
      const index = e.currentTarget.dataset.index;
      const selected = this.data.selectedTemplates.includes(index)
        ? this.data.selectedTemplates.filter(i => i !== index)
        : [...this.data.selectedTemplates, index];
  
      this.setData({ selectedTemplates: selected });
    },
     /* 知识库选择 */
    onKnowledgeBaseChange(e) {
        const selectedIndex = e.detail.value;
        const selectedKnowledgeBase = this.data.categories[selectedIndex];
        const db_id= this.data.categories[selectedIndex].db_id
        this.setData({
          selectedKnowledgeBase: selectedIndex,
          selecteDbId:db_id,
          'formData.title': selectedKnowledgeBase.name // 如果需要将选中的知识库名称赋值给 formData.title
        });
    },
});
  